package ru.dadle8.service.impl.callback.workout;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.dadle8.model.bot.type.CallbackAction;
import ru.dadle8.model.db.Workout;
import ru.dadle8.service.impl.callback.AbstractCallbackService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BackWorkoutCallbackServiceImpl extends AbstractCallbackService {

    @Override
    public void processUpdate(Update update) throws TelegramApiException {
        if (getCallbackData().num() == -1) {
            getBot().execute(getMessageHelper().sendMessage(getChatId(), "Больше тренировок нет. Это первая страница"));
        } else {
            Page<Workout> workouts = getWorkoutService().findAllWorkouts(getCallbackData().num());

            InlineKeyboardMarkup inlineKeyboardMarkup = getKeyboardService().getInlineKeyboardMarkupWithPagination(
                    workouts.stream().map(Workout::getTitle).collect(Collectors.toList()),
                    workouts.stream().map(Workout::getMessageId).collect(Collectors.toList()),
                    getCallbackData().num());
            getBot().execute(getMessageHelper().sendEditMessageText(getChatId(), getMessageId(), "Выбери тренировку. Страница №%s".formatted(getCallbackData().num()+1), inlineKeyboardMarkup));
        }

        getBot().execute(getMessageHelper().sendAnswerCallbackQuery(getCallbackQuery()));
    }

    @Override
    public int getAction() {
        return CallbackAction.WORKOUT_BACK.getAction();
    }
}
